import { api, LightningElement, track } from 'lwc';


export default class TestLwcIf extends LightningElement {

    isLoading = false;

    @track dataRows = [];
    // dataRows = [];

    @api records;

    @api columns;

    @api freezeColumns;

    connectedCallback() {
        if(this.records && Array.isArray(this.records)) {
            this.reloadData(this.records);
        }
    }

    @api
reloadData(records) {
    if(records && Array.isArray(records)) {
        // 一定要在更新数据前先清空旧数据，然后在异步线程中更新数据，重新渲染DOM
        // 否则DOM状态不一致，会报错：Uncaught (in promise) TypeError: Failed to execute 'removeChild' on 'Node': parameter 1 is not of type 'Node'.
        this.dataRows.splice(0);
        this.isLoading = true;
        setTimeout(() => {
            this.dataRows = JSON.parse(JSON.stringify(records));
            this.isLoading = false;
        }, 0);
    }
}

    toggleRowExpand(event) {
        // 1. change button icon
        // 2. hide/show children row
        let target = event.target;
        let iconName = target.iconName;
        let idx = target.dataset.idx;
        console.log('idx: ' + idx +', iconName: ' + iconName);
        if(iconName === 'utility:chevrondown') {
            // Collapse children row
            target.iconName = 'utility:chevronright';
            this.dataRows[idx].expanded = false;
        } else {
            // Expand children row
            target.iconName = 'utility:chevrondown';
            this.dataRows[idx].expanded = true;
        }
    }
}